import type {FC} from 'react';
import React, {useRef, useState} from 'react';
import {DownOutlined, PlusOutlined} from '@ant-design/icons';
import {
  Avatar,
  Button,
  Card,
  Image,
  Dropdown,
  Input,
  List,
  Menu, message,
  Modal,
  Progress,
  Radio,
  Steps,
} from 'antd';

import {PageContainer} from '@ant-design/pro-layout';
import {useRequest} from 'umi';
import moment from 'moment';
import OperationModal from './components/OperationModal';
import {
  addAbApplyList,
  addFakeList,
  getAbApplyStatus,
  queryAbApplyList,
  queryFakeList,
  removeFakeList,
  updateFakeList
} from './service';
import type {BasicListItemDataType} from './data.d';
import styles from './style.less';
import {red, green} from '@ant-design/colors';
import {bindWechat} from "@/pages/Account/Settings/service";
import {ApplyListItem} from "./data.d";

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const {Search} = Input;

const Info: FC<{
  title: React.ReactNode;
  value: React.ReactNode;
  bordered?: boolean;
}> = ({title, value, bordered}) => (
  <div className={styles.headerInfo}>
    <span>{title}</span>
    <p>{value}</p>
    {bordered && <em/>}
  </div>
);
let statusText = {
  10: "申请",
  20: "核查",
  30: "受理",
  40: "评价",
  50: "公示",
  60: "发证",
  70: "复核1",
  80: "复核2"
}

const ListContent = ({
                       data: {enterpriseName, createTime, status, level, cert},
                     }: {
  data: BasicListItemDataType;
}) => (
  <div className={styles.listContent}>
    <div className={styles.listContentItem}>
      {
        (cert) ?
          <>
            <Image
              width={60}
              src={cert}
            />
          </>
          : <></>
      }
    </div>
    {/*<div className={styles.listContentItem}>*/}
    {/*  <span>企业名称</span>*/}
    {/*  <p>{enterpriseName}</p>*/}
    {/*</div>*/}
    <div className={styles.listContentItem}>
      <span>级别</span>
      <p>{level}</p>
    </div>
    <div className={styles.listContentItem}>
      <span>申请时间</span>
      <p>{createTime}</p>
    </div>
    <div className={styles.listContentItem}>
      <Progress percent={(status) / 80 * 100} format={percent => statusText[status]} status={status} strokeWidth={10}
                style={{width: 180}}
                strokeColor={["red"]}
                steps={8}/>
    </div>
  </div>
);

export const BasicList: FC = () => {
  const [done, setDone] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<Partial<BasicListItemDataType> | undefined>(undefined);
  const [visibleStatus, setVisibleStatus] = useState<boolean>(false);
  const [currentData, setCurrentData] = useState<ApplyListItem>({status: 0, statusData: []});

  const {
    data: listData,
    loading,
    mutate,
  } = useRequest(() => {
    return queryAbApplyList();
  });
  const {run: postRun} = useRequest(
    (method, params) => {
      if (method === 'remove') {
        return removeFakeList(params);
      }
      if (method === 'update') {
        return updateFakeList(params);
      }
      if (method === 'add') {
        return addAbApplyList(params);
      }
      return addFakeList(params);
    },
    {
      manual: true,
      onSuccess: (result) => {
        mutate(result);
      },
    },
  );

  console.log(listData, "333")
  const list = listData || [];

  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    pageSize: 5,
    total: list.length,
  };

  const showEditModal = async (item: ApplyListItem) => {
    // let data = await getAbApplyStatus(item.applyId);
    setCurrentData(item);
    setVisibleStatus(true);
  };

  const deleteItem = (id: string) => {
    postRun('remove', {id});
  };

  const editAndDelete = (key: string | number, currentItem: BasicListItemDataType) => {
    if (key === 'edit') showEditModal(currentItem);
    else if (key === 'delete') {
      Modal.confirm({
        title: '删除任务',
        content: '确定删除该任务吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => deleteItem(currentItem.id),
      });
    }
  };

  const extraContent = (
    <div className={styles.extraContent}>
      <Button
        key="ab-apply"
        type="primary"
        onClick={() => {
          setVisible(true)
        }}
      >
        <PlusOutlined/>
        申请安全生产标准化
      </Button>
    </div>
  );

  const MoreBtn: React.FC<{
    item: BasicListItemDataType;
  }> = ({item}) => (
    <Dropdown
      overlay={
        <Menu onClick={({key}) => editAndDelete(key, item)}>
          <Menu.Item key="edit">编辑</Menu.Item>
          <Menu.Item key="delete">删除</Menu.Item>
        </Menu>
      }
    >
      <a>
        更多 <DownOutlined/>
      </a>
    </Dropdown>
  );

  const handleDone = () => {
    setDone(false);
    setVisible(false);
    setCurrent({});
  };

  const handleSubmit = async (values: BasicListItemDataType) => {
    console.log(values)
    const hide = message.loading('申请提交中', 0);
    let data = await addAbApplyList(values);
    hide();
    if (data.code === 200) {
      message.success('提交成功');
      setDone(true);
    } else {
      message.error(data.msg);
    }
    // const method = values?.id ? 'update' : 'add';
    // let postRun1 = postRun("add", values).then(function (ssss) {
    //   console.log(ssss,"23")
    //
    // });
    // console.log(postRun1.then)
  };

  return (
    <div>
      <Modal visible={visibleStatus} onCancel={() => {
        setVisibleStatus(false)
      }} destroyOnClose={true} maskClosable={false} title={'进度'} footer={null}>
        <div style={{padding: '0px 20px', width: '200px', margin: '0 auto'}}>
          <Steps progressDot current={currentData.status / 10} direction={'vertical'}>
            <Steps.Step title="申请" description={currentData.statusData[10] ? currentData.statusData[10].text : ''}/>
            <Steps.Step title="核查" description={currentData.statusData[20] ? currentData.statusData[20].text : ''}/>
            <Steps.Step title="受理" description={currentData.statusData[30] ? currentData.statusData[30].text : ''}/>
            <Steps.Step title="评价" description={currentData.statusData[40] ? currentData.statusData[40].text : ''}/>
            <Steps.Step title="公示" description={currentData.statusData[50] ? currentData.statusData[50].text : ''}/>
            <Steps.Step title="发证" description={currentData.statusData[60] ? currentData.statusData[60].text : ''}/>
            <Steps.Step title="复核1" description={currentData.statusData[70] ? currentData.statusData[70].text : ''}/>
            <Steps.Step title="复核2" description={currentData.statusData[80] ? currentData.statusData[80].text : ''}/>
          </Steps>
        </div>
      </Modal>
      <PageContainer waterMarkProps={{content: ''}} content={<div>
        <p>
          安全生产标准化申请流程如下：
        </p>
        <div style={{padding: '40px'}}>
          <Steps progressDot current={7}>
            <Steps.Step title="申请"/>
            <Steps.Step title="核查"/>
            <Steps.Step title="受理"/>
            <Steps.Step title="评价"/>
            <Steps.Step title="公示"/>
            <Steps.Step title="发证"/>
            <Steps.Step title="复核1"/>
            <Steps.Step title="复核2"/>
          </Steps>
        </div>
      </div>}>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title="申请记录"
            style={{marginTop: 24}}
            bodyStyle={{padding: '0 32px 40px 32px'}}

            extra={extraContent}
          >

            {/*<Button*/}
            {/*  type="dashed"*/}
            {/*  onClick={() => {*/}
            {/*    setVisible(true);*/}
            {/*  }}*/}
            {/*  style={{width: '100%', marginBottom: 8, height: "80px"}}*/}
            {/*>*/}
            {/*  <PlusOutlined/>*/}
            {/*  申请安全生产标准化*/}
            {/*</Button>*/}
            <List
              size="large"
              rowKey="id"
              loading={loading}
              pagination={paginationProps}
              dataSource={list}
              renderItem={(item) => (
                <List.Item
                  actions={[
                    <Button type={'link'} size={'small'} onClick={(e) => {
                      e.preventDefault();
                      showEditModal(item).then(r => {
                      });
                    }}>进度</Button>
                  ]}
                >
                  <List.Item.Meta
                    avatar={<Avatar src="/ab.svg" shape="square" size="large"/>}
                    title={`安全生产标准化【${item.enterpriseName}】`}
                    description={`${item.typeName},${item.categoryName}`}
                  />
                  <ListContent data={item}/>
                </List.Item>
              )}
            />
          </Card>
        </div>
      </PageContainer>

      <OperationModal
        done={done}
        visible={visible}
        current={current}
        onDone={handleDone}
        onSubmit={handleSubmit}
      />
    </div>
  );
};

export default BasicList;
